package com.epoch.base.util;

import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.xml.bind.DatatypeConverter;

import org.apache.commons.lang3.StringUtils;

import com.epoch.platform.sys.dict.dao.SysDict;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

public class EmailUtils {
	/**
	 * 根据数据字典判断当前环境然后调用发送邮件方法
	 * @param toEmail
	 * @param ccEmail
	 * @param title
	 * @param htmlContent
	 * @param fromEmail
	 * @param files
	 * @return
	 */
	public static Boolean sendMail(String toEmail, String ccEmail, String title, String htmlContent,String... files){
		String mail=null;
		SysDict dictControl = SysDict.dao.find(Db.getSqlPara("systemManage.findSysDictByParams", Kv.by(SysDict.DICT_CODE, "EMAIL_CONTROL")
                .set(SysDict.ITEM_FLAG, "Y")
                .set(SysDict.HEAD_FLAG, "N"))).get(0);
		String control=dictControl.getStr(SysDict.ITEM_CODE);
		SysDict dictMail = SysDict.dao.find(Db.getSqlPara("systemManage.findSysDictByParams", Kv.by(SysDict.DICT_CODE, "EMAIL_FROM")
                .set(SysDict.ITEM_FLAG, "Y")
                .set(SysDict.HEAD_FLAG, "N"))).get(0);
		if(dictMail.get(SysDict.ITEM_CODE)!=null){
			mail=dictMail.getStr(SysDict.ITEM_CODE);
		}
		if(StringUtils.isBlank(mail)){
			mail="ext@hk.chinamobile.com";
		}
//		if("true".equals(control)){
//			return EmailUtil.sendEmailUat(toEmail, ccEmail, title, htmlContent, mail, files);
//		}else{
//			return	EmailUtil.sendEmail(toEmail, ccEmail, title, htmlContent, files);
//		}
		return null;
	}
	
    /**
     * 邮件发送方法，邮件内容HTML。可包含附件
     * @param host 服务器地址
     * @param port 端口
     * @param isAuth 是否用户校验
     * @param isSSL 是否加密
     * @param userName 用户名
     * @param password 密码
     * @param toMail 收件人邮箱，多个用分号分隔
     * @param ccMail 抄送人邮箱，多个用分号分割
     * @param subject 标题
     * @param content html内容
     * @param files 附件路径，可以包含多个附件
     * @param isUat "true":为是uat环境,"false":为是sit，dev环境
     * @return 发送邮件是否成功返回信息，true是成功，false失败
     */
    public static boolean sendMail(String host, int port, boolean isAuth, boolean isSSL, String userName, String password, String toMail, String ccMail, String subject, String content,
        Boolean isUat,String... files) {
        boolean isFlag = false;
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", host);
            if(isUat){
            	  props.put("mail.smtp.auth", false);
            }else{
	            props.put("mail.smtp.auth", isAuth);
	            props.put("mail.smtp.ssl.enable", isSSL);
            }
            Session session = Session.getDefaultInstance(props);
            session.setDebug(false);

            MimeMessage message = new MimeMessage(session);
            /*设置发件人*/
            message.setFrom(new InternetAddress(userName));
            /*设置收件人*/
            if (StrKit.notBlank(toMail)) {
                String[] tos = toMail.split(";");
                int toCnt = tos.length;
                Address[] toAdds = new Address[toCnt];
                for (int i = 0; i < toCnt; i++) {
                    toAdds[i] = new InternetAddress(tos[i]);
                }
                message.addRecipients(Message.RecipientType.TO, toAdds);
            }
            /*设置抄送人*/
            if (StrKit.notBlank(ccMail)) {
                String[] ccs = ccMail.split(";");
                Address[] ccAddresses = new InternetAddress[ccs.length];
                for (int i = 0; i < ccs.length; i++) {
                    ccAddresses[i] = new InternetAddress(ccs[i]);
                }
                message.addRecipients(Message.RecipientType.CC, ccAddresses);
            }
            message.setSubject(subject);
            message.addHeader("charset", "UTF-8");

            /*添加正文内容*/
            Multipart multipart = new MimeMultipart();
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setText(content);

            contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
            multipart.addBodyPart(contentPart);

            /*添加附件*/
            for (String file : files) {
                File usFile = new File(file);
                MimeBodyPart fileBody = new MimeBodyPart();
                DataSource source = new FileDataSource(file);
                fileBody.setDataHandler(new DataHandler(source));
                fileBody.setFileName("=?UTF-8?B?" + DatatypeConverter.printBase64Binary(usFile.getName().getBytes()) + "?=");
                multipart.addBodyPart(fileBody);
            }

            message.setContent(multipart);
            message.setSentDate(new Date());
            message.saveChanges();
            if(isUat){
            	Transport.send(message, message.getAllRecipients());
            }else{
            Transport transport = session.getTransport("smtp");
            transport.connect(host, port, userName, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            }
            isFlag = true;
        } catch (Exception e) {
            //LOGGER.error("send mail failed", e);
        }
        return isFlag;
    }
	
    /**
     * 邮件发送接口对外调用接口 sit dev
     * @param toEmail 收件人地址，多个用分号分隔
     * @param ccEmail 抄送人地址，多个用分号分隔
     * @param title 邮件标题
     * @param htmlContent 邮件内容HTML格式
     * @param files 邮件附件，可以包含多个附件
     * @return 发送邮件是否成功返回信息，true是成功，false失败
     */
    public static boolean sendEmail(String toEmail, String ccEmail, String title, String htmlContent, String... files) {
        String emailServer = PropKit.use("application.properties").get("pccw.message.mail.smtp.host");
        String fromEmail = PropKit.use("application.properties").get("pccw.message.mail.auth.username");
        String password = PropKit.use("application.properties").get("pccw.message.mail.auth.password");
        boolean needSSL = PropKit.use("application.properties").getBoolean("pccw.message.mail.SSLenable");
        boolean enable = PropKit.use("application.properties").getBoolean("mail.smtp.starttls.enable");
        int smtpPort = PropKit.use("application.properties").getInt("pccw.mail.smtp.port");
        return sendMail(emailServer, smtpPort, enable, needSSL, fromEmail, password, toEmail, ccEmail, title, htmlContent, false,files);
    }
    /**
     * 邮件发送接口对外调用接口 uat
     * @param toEmail
     * @param ccEmail
     * @param title
     * @param htmlContent
     * @param files
     * @param fromEmail
     * @return
     */
    public static boolean sendEmailUat(String toEmail, String ccEmail, String title, String htmlContent, String fromEmail,String... files){
    	 String emailServer = PropKit.use("application.properties").get("pccw.message.mail.smtp.host");
         String password = PropKit.use("application.properties").get("pccw.message.mail.auth.password");
         boolean needSSL = PropKit.use("application.properties").getBoolean("pccw.message.mail.SSLenable");
         boolean enable = PropKit.use("application.properties").getBoolean("mail.smtp.starttls.enable");
         int smtpPort = PropKit.use("application.properties").getInt("pccw.mail.smtp.port");
     	return sendMail(emailServer, smtpPort, enable, needSSL, fromEmail, password, toEmail, ccEmail, title, htmlContent,true,files);
    }
}
